package com.suning.park.admin.mgr.permissions.controller;

import com.suning.park.dto.model.Role;
import com.suning.park.dto.model.Vali;
import com.suning.park.admin.util.JsonUtil;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.admin.util.page.PageResult;
import com.suning.park.admin.base.BasicData;
import com.suning.park.admin.databasespec.model.SpecFunctionSource;
import com.suning.park.admin.exception.BusinessFailException;
import com.suning.park.admin.mgr.permissions.service.FuncTreeService;
import com.suning.park.admin.mgr.permissions.service.RoleService;
import com.suning.park.admin.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理模块接口
 * @author niecheng
 */
@Controller
@RequestMapping(value = "/mgr/role")
public class RoleController implements BasicData {

    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Resource(name = "roleServiceImpl")
    protected RoleService roleService;

    @Resource(name = "funcTreeServiceImpl")
    protected FuncTreeService funcTreeService;

    @RequestMapping(value="/list")
    public ModelAndView list(
            @RequestParam(value = "positionName", required = false) String positionName,
            @ModelAttribute("page") PageInfo page, ModelAndView view) {
            view.setViewName("role/list");
        return view;
    }

    @RequestMapping(value="/addUI", method = RequestMethod.GET)
    public ModelAndView addUI(ModelAndView view){
        view.setViewName("role/add");
        return view;
    }

    /**
     * 查看
     *
     * @param view
     * @return
     */
    @RequestMapping(value = "roleAndTreeUI", method = RequestMethod.GET)
    public ModelAndView roleAndTreeUI(ModelAndView view) {
        logger.info("获取系统所有角色");
        try {
            List<Role> roles = roleService.getRole();
            view.addObject(IS_SUCCESS_DESC, true);
            view.addObject("auRoleId", "0");
            view.addObject("roles", roles);
        }catch (Exception e) {
            logger.error("获取系统所有角色 程序异常, 失败信息：{}", new Object[]{e.getMessage()});
            view.addObject(IS_SUCCESS_DESC, false);
            view.addObject(MESSAGE_DESC, e.getMessage());
        }
        view.setViewName("role/roleFuncTree");
        return view;
    }

    @ResponseBody
    @RequestMapping(value="roleAndTree",method = RequestMethod.POST)
    public  Map<String, Object> roleAndTree(String roleId,String functionSourceIds){
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Date currentDate = new Date();
        logger.info("角色授权，角色ID：{}, 资源IDS：{}", new Object[]{roleId, functionSourceIds});
        roleService.saveRoleFunctree(roleId, functionSourceIds.split(","), currentDate);
        resultMap.put(IS_SUCCESS_DESC, true);
        resultMap.put(MESSAGE_DESC, "授权成功");
        return resultMap;
    }

    /**
     * 异步获取系统对应角色
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/initAurole", method = RequestMethod.POST)
    public Map<String, Object> initAurole(){
        Map<String, Object> resMap = new HashMap<String, Object>();
        List<Role> roleList = null;
        try{
            roleList = roleService.getRole();
            resMap.put(IS_SUCCESS_DESC, true);
            resMap.put("roleList", roleList);
            resMap.put("msg", "获取信息成功");
        }catch (Exception e){
            resMap.put(IS_SUCCESS_DESC, false);
            resMap.put(MESSAGE_DESC, "后台异常");
        }
        return resMap;
    }


    /**
     * 角色管理列表信息查询
     * @param draw
     * @param pageInfo
     * @param positionName 资源名称
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/ajaxList", method = RequestMethod.POST)
    public PageResult uesrlist(@RequestParam(value = "draw") int draw,
                               PageInfo pageInfo,
                               @RequestParam(value = "positionName", required = false) String positionName) {
        logger.info("角色管理列表信息，角色名称：{}",positionName);
        Map<String, Object> params = new HashMap<>();
        try {
            if(StringUtils.isNotBlank(positionName)){
                params.put("positionName", positionName.trim());
            }
            pageInfo = roleService.queryByPage(params, pageInfo);
        } catch (BusinessFailException se) {
            logger.error("角色管理列表信息 业务异常, 失败信息：{}，资源名称：{}", new Object[]{se.getMessage(), positionName});
            return null;
        } catch (Exception e) {
            logger.error("角色管理列表信息 程序异常, 失败信息：{}, 资源名称：{}", new Object[]{e.getMessage(), positionName});
            return null;
        }
        return new PageResult(pageInfo, draw);
    }

    /**
     * ajax验证角色是否存在
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/isExistByName", method = RequestMethod.POST)
    public  boolean isExistByName(@RequestParam("sPositionName") String sPositionName) {
        if(StringUtil.hasEmpty(sPositionName)){
            return false;
        }
        return !roleService.isExistByName(sPositionName);
    }

    /**
     * 编辑
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public Map<String, Object> edit( Role role) {
        Date currentDate = new Date();
        Map<String, Object> result = new HashMap<>();
        logger.info("编辑角色信息：{}", JsonUtil.objectToJson(role));
        try {
            roleService.update(role, currentDate);
            result.put(IS_SUCCESS_DESC, false);
            result.put(MESSAGE_DESC, "修改成功");
        }catch (Exception e) {
            logger.error("编辑角色信息 程序异常, 失败信息：{}", new Object[]{e.getMessage()});
            result.put(IS_SUCCESS_DESC, false);
            result.put(MESSAGE_DESC, "修改失败");
        }
        return result;
    }



    /**
     * 添加角色
     * @param role
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String,Object> add(Role role) {
        Map<String, Object> result = new HashMap<>();
        Date currentDate = new Date();
        logger.info("添加角色信息：{}", JsonUtil.objectToJson(role));
        String msg = checkParmas(role);
        if(!StringUtil.hasEmpty(msg)){
            result.put(IS_SUCCESS_DESC, BUSINESS_FAIL);
            result.put(MESSAGE_DESC, msg);
            return result;
        }
        roleService.addRole(role, currentDate);
        result.put(IS_SUCCESS_DESC, SUCCESS);
        result.put(MESSAGE_DESC, "添加成功");
        return result;
    }

    /**
     * 参数校验
     * @param role
     * @return
     */
    private String checkParmas(final Role role){
        String msg = "";
        if(StringUtil.isEmpty(role.getRemark())){
            msg+= "备注不能为空, ";
        }
        if(StringUtil.isEmpty(role.getPositionName())){
            msg+="名称不能为空, ";
        }
        if(roleService.isExistByName(role.getPositionName())){
            msg+="角色名称已存在";
        }
        return msg;
    }

    /**
     * 异步获取所有资源信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getRoleAndTree/{roleId}")
    public  Map<String, Object> getRoleAndTree(@PathVariable("roleId")String roleId){
        logger.info("异步获取所有资源信息，角色ID：{}", roleId);
        Map<String, Object> result = new HashMap<String, Object>();
        if(StringUtil.hasEmpty(roleId)){
            result.put(IS_SUCCESS_DESC, false);
            result.put(MESSAGE_DESC, "请选择角色");
            return result;
        }
        try{
            List<Vali> araList = roleService.getVali(roleId);
            SpecFunctionSource specAssFunctionSource = new SpecFunctionSource();
            specAssFunctionSource.setCode(AU_FUNC_TREE_ROOT_ID);
            List<SpecFunctionSource> specFunctionSource = funcTreeService.selectSpecByParentCodeForRoleAuth(specAssFunctionSource, null);
            result.put(IS_SUCCESS_DESC, true);
            result.put("roleResList", araList);
            result.put("resourceList", specFunctionSource);
        }catch (Exception e){
            result.put(IS_SUCCESS_DESC, false);
            result.put(MESSAGE_DESC, "后台异常");
            return result;
        }
        return result;
    }

    @RequestMapping(value="/editUI/{roleId}", method = RequestMethod.GET)
    public ModelAndView editUI(ModelAndView view, @PathVariable("roleId")String roleId){
        logger.info("编辑获取角色获取资源信息，角色ID：{}", roleId);
        try{
            view.addObject("object", roleService.selectRole(roleId).get(0));
        }catch (Exception e){
            logger.error("编辑获取角色获取资源信息 程序错误 ， 错误信息：{}，角色ID：{}", e.getMessage(), roleId);
        }
        view.setViewName("role/edit");
        return view;
    }
}
